<template>
    <div class="plan">
        <el-table
            id="cfscntr-table-cfscntr"
            ref="tableRef"
            :data="tableData"
            v-bind="tableDefaultAttribute"
            :max-height="tableHeight"
            row-key="id"
            table-layout="auto"
            highlight-current-row
            @current-change="handleCurrentChange"
        >
            <template #empty>
                <span>无数据</span>
            </template>

            <template v-for="col in tableColumns" :key="col.prop">
                <el-table-column
                    v-if="!col.isHidden"
                    :align="col.align"
                    :prop="col.prop"
                    :label="col.label"
                    :formatter="col.formatter"
                    :type="col.type"
                    :fixed="col.fixed"
                    :width="col.width"
                >
                </el-table-column>
            </template>
        </el-table>
    </div>
    <div class="cntr">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            :size="'default'"
            status-icon
        >
            <el-row :gutter="2">
                <el-col :span="6">
                    <el-form-item label="箱号" prop="cntr">
                        <template v-if="allowedCntrs.length === 0">
                            <textupperinput
                                v-model.trim="formData.cntr"
                            ></textupperinput>
                        </template>
                        <template v-else>
                            <el-select
                                v-model.trim="formData.cntr"
                                :clearable="true"
                                filterable
                                placeholder="输入箱号"
                            >
                                <el-option
                                    v-for="optValue in allowedCntrs"
                                    :key="optValue.value"
                                    :label="optValue.value"
                                    :value="optValue.value"
                                >
                                </el-option>
                            </el-select>
                        </template>
                    </el-form-item>
                </el-col>

                <el-col :span="4">
                    <el-form-item label="箱况" prop="dam_id">
                        <el-select v-model="formData.dam_id" :clearable="true">
                            <el-option
                                v-for="optValue in cntrDam"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="尺寸" prop="cntr_siz_cod">
                        <el-select
                            v-model="formData.cntr_siz_cod"
                            :clearable="true"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cntrSiz"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱型" prop="cntr_typ_cod">
                        <el-select
                            v-model="formData.cntr_typ_cod"
                            :clearable="true"
                            disabled
                        >
                            <el-option
                                v-for="optValue in cntrTyp"
                                :key="optValue.value"
                                :label="optValue.value"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="收箱提单号" prop="bill_no">
                        <!-- <el-input v-model.trim="formData.bill_no" /> -->
                        <textupperinput
                            v-bind="{ disabled: true }"
                            v-model.trim="formData.bill_no"
                        ></textupperinput>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="2">
                <el-col :span="6">
                    <el-form-item label="进场日期" prop="to_port_tim">
                        <el-date-picker
                            v-model="formData.to_port_tim"
                            type="datetime"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="车号" prop="out_truck_no_c">
                        <el-input v-model.trim="formData.out_truck_no_c" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="司机电话" prop="out_truck_tel">
                        <el-input v-model.trim="formData.out_truck_tel" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="formData.remark" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="2" v-if="displayControl">
                <el-col :span="4">
                    <el-form-item label="箱制造日期" prop="cntr_date">
                        <el-date-picker
                            v-model="formData.cntr_date"
                            type="date"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱皮重" prop="cntr_new_wgt">
                        <el-input-number v-model="formData.cntr_new_wgt" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="箱载重" prop="scale_wgt">
                        <el-input-number v-model="formData.scale_wgt" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="2" v-if="displayControl">
                <el-col :span="4">
                    <el-form-item label="进场船名" prop="in_ship_nam">
                        <el-input v-model.trim="formData.in_ship_nam" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="进场航次" prop="in_voyage">
                        <el-input v-model.trim="formData.in_voyage" />
                    </el-form-item>
                </el-col>

                <el-col :span="4">
                    <el-form-item label="机组品牌" prop="refmachine_brand">
                        <el-input v-model.trim="formData.refmachine_brand" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="机组型号" prop="refmachine_model">
                        <el-input v-model.trim="formData.refmachine_model" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="机组日期" prop="refmachine_date">
                        <el-date-picker
                            v-model="formData.refmachine_date"
                            type="date"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row> </el-row>
        </el-form>
    </div>

    <div class="btn-group">
        <el-button-group>
            <el-button class="btn" type="primary" v-debounce="save" size="large"
                >进场</el-button
            >
            <el-button
                class="btn"
                type="primary"
                @click="onRefresh"
                size="large"
                >刷新</el-button
            >
        </el-button-group>
    </div>
</template>
<script setup lang="ts" name="CfsCntr">
import { ref, reactive, onMounted, computed } from 'vue';
import { storeToRefs } from 'pinia';
import {
    type FormInstance,
    type FormRules,
    type TableRefs,
} from 'element-plus';
import type { CntrModel, PlanModel } from '@/common/types/container';
import { Request } from '@/app/request';
import { useAppStore } from '@/store/app';
import { tableDefaultAttribute, tableColumnDefault } from '@/hooks/useTable';
import { formatDate, transFormatter, validateCntr } from '@/common/tools';
import { isEmpty } from 'lodash';
import { ValidateFieldsError } from 'async-validator';
import textupperinput from '@/components/forms/TextUpperInput.vue';
import { TableColumn, SelectOption } from '@/common/types/app';

const {
    cntrDam,
    cntrSiz,
    cntrTyp,
    cyCfs,
    cntrOwner,
    SelectOptionYN,
    cntrOper,
    cntrGateInStat,
} = storeToRefs(useAppStore());

const formRef = ref<FormInstance>();
const formData = reactive<CntrModel>({});
const tableRef = ref<TableRefs>();
const tableData = ref<PlanModel[]>([]);
const tableHeight = ref(100);
const allowedCntrs = ref<SelectOption[]>([]);
const currentRow = ref<PlanModel>(); // 用于存储当前选中的行
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'cntr_oper_cod') {
        data = cntrOper.value;
    } else if (column['property'] === 'dam_id') {
        data = cntrDam.value;
    } else if (column['property'] === 'stat_cod') {
        data = cntrGateInStat.value;
    } else if (column['property'] === 'cfs_cod') {
        data = cyCfs.value;
    } else if (column['property'] === 'cntr_owner') {
        data = cntrOwner.value;
    } else if (column['property'] === 'finish_id') {
        data = SelectOptionYN.value;
    } else if (column['property'] === 'need_email') {
        data = SelectOptionYN.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'id',
        label: '计划号',
        fixed: 'left',
        formFieldItemType: 'input',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'plan_name',
        label: '计划名称',
        sortable: 'custom',
        fixed: 'left',
        formFieldItemType: 'input',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'plan_date',
        label: '计划进场日期',
        sortable: 'custom',
        formatter: formatDate,
        formFieldItemType: 'date',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 8,
        prop: 'stat_cod',
        label: '作业目的',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrGateInStat.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'cntr_siz_cod',
        label: '箱尺寸',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'cntr_typ_cod',
        label: '箱型',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 7,
        prop: 'cntr_num',
        label: '箱量',
        sortable: 'custom',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'bill_no',
        label: '提箱单号',
        sortable: 'custom',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 12,
        prop: 'dam_id',
        label: '箱况',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrDam.value,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'in_reason',
        label: '进箱原因',
        sortable: 'custom',
        width: 200,
    },

    {
        ...tableColumnDefault,
        order: 15,
        prop: 'cntr_owner',
        label: '箱主',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrOwner.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 16,
        prop: 'cntr_work_num',
        label: '已作业箱量',
        sortable: 'custom',
        width: 120,
    },
    {
        ...tableColumnDefault,
        order: 18,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
        width: 400,
    },
]);
const rules = reactive<FormRules>({
    cntr: [
        { required: true, message: '请输入箱号', trigger: 'blur' },
        { validator: validateCntr, trigger: 'blur' },
    ],

    dam_id: [{ required: true, message: '请输入好坏', trigger: 'blur' }],
    cntr_siz_cod: [{ required: true, message: '请输入尺寸', trigger: 'blur' }],
    cntr_typ_cod: [{ required: true, message: '请输入箱型', trigger: 'blur' }],
    cfs_cod: [{ required: true, message: '请输入站点', trigger: 'blur' }],
    to_port_tim: [
        { required: true, message: '请输入进场时间', trigger: 'blur' },
    ],
    /* bill_no: [{ required: true, message: '请输入收箱提单号', trigger: 'blur' }],
    cntr_owner: [{ required: true, message: '请输入箱主', trigger: 'blur' }], */
});
const displayControl = computed(() => {
    if (currentRow.value?.stat_cod === 'EIDXJC') {
        return true;
    }
    return false;
});
const onRefresh = async () => {
    formRef.value?.resetFields();
    currentRow.value = undefined;
    // formData.trade_id = '1'; // 外贸
    // formData.e_f_id = 'E';
    formData.dam_id = 'AV';
    formData.in_dam_id = 'AV';
    // formData.in_truck_no_c = '鲁B';
    const req = new Request('堆场未完成进场计划查询');
    const r = await req.post();

    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};

onMounted(() => {
    // tableHeight.value = window.innerHeight - tableMaxHeightAdjust - 280;
    tableHeight.value = Math.floor((window.innerHeight / 3) * 2);
    onRefresh();
});
const copyPlanData = () => {
    formData.in_dam_id = currentRow.value?.dam_id;
    formData.dam_id = currentRow.value?.dam_id;
    formData.cntr_siz_cod = currentRow.value?.cntr_siz_cod;
    formData.cntr_typ_cod = currentRow.value?.cntr_typ_cod;
    formData.cntr_oper_cod = currentRow.value?.cntr_oper_cod;
    formData.cfs_cod = currentRow.value?.cfs_cod;
    formData.bill_no = currentRow.value?.bill_no;
    formData.free_days = currentRow.value?.free_days;
    formData.cntr_owner = currentRow.value?.cntr_owner;
    formData.in_truck_sn = currentRow.value?.id;
    formData.stat_cod = currentRow.value?.stat_cod;
};
const handleCurrentChange = async (val: PlanModel | undefined) => {
    formRef.value?.resetFields();
    currentRow.value = val; // 更新当前选中的行

    copyPlanData();
    allowedCntrs.value.length = 0;
    if (val?.id) {
        const req = new Request('堆场未完成计划预定箱查询', {
            plan_id: val?.id,
        });
        const r = await req.post();

        if (!isEmpty(r.obj)) {
            allowedCntrs.value = r.obj;
        }
    }
};
const save = async () => {
    const formValid = await formRef.value?.validate(
        (isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
            return;
        },
    );
    if (formValid) {
        if (formData.stat_cod === 'EIDXJC' || formData.stat_cod === 'ESPTID') {
            const req = new Request('闸口箱进场', {
                cntr: formData.cntr,
                stat_cod: formData.stat_cod,
                in_truck_sn: formData.in_truck_sn,
                dam_id: formData.dam_id,
                cntr_net_wgt: formData.cntr_net_wgt,
                to_port_tim: formData.to_port_tim,
                cntr_date: formData.cntr_date,
                refmachine_brand: formData.refmachine_brand,
                refmachine_model: formData.refmachine_model,
                refmachine_date: formData.refmachine_date,
                in_ship_nam: formData.in_ship_nam,
                in_voyage: formData.in_voyage,
                scale_wgt: formData.scale_wgt,
            });
            const r = await req.post();
            if (r.code > 100) {
                onRefresh();
            }
        }
        if (formData.stat_cod === 'EITZJC') {
            const req = new Request('闸口退租箱进场', {
                cntr: formData.cntr,
                rent_sn: formData.in_truck_sn,
                dam_id: formData.dam_id,
                back_date: formData.to_port_tim,
                back_truck_no_c: formData.out_truck_no_c,
                back_driver_tel: formData.out_truck_tel,
            });
            const r = await req.post();

            if (r.code > 100) {
                onRefresh();
            }
        }
        if (formData.stat_cod === 'EIZYXT') {
            
            const req = new Request('闸口调箱进场', {
                cntr: formData.cntr,
                rent_sn: formData.in_truck_sn,
                dam_id: formData.dam_id,
                back_date: formData.to_port_tim,
                back_truck_no_c: formData.out_truck_no_c,
                back_driver_tel: formData.out_truck_tel,
            });
            const r = await req.post();

            if (r.code > 100) {
                onRefresh();
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.cntr {
    margin-bottom: 20px;
    padding: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.plan {
    margin-bottom: 20px;
    padding-top: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.btn-group {
    .btn {
        margin-right: 5px;
    }
}
</style>
